package defineProduct.controller;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.DatabaseException;
import model.User;

import com.google.gson.Gson;

import defineProduct.model.ItemBean;

/**
 * Servlet implementation class DescribeSizes4
 */
@WebServlet("/DescribeSizes4")
public class DescribeSizes4 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		if(user==null || !user.getAccountType().equals("S")){
			response.sendRedirect("Login.html");
			return;
		}
		request.setCharacterEncoding("UTF-8");
		Map<String, String[]> parameterMap = request.getParameterMap();

		ItemBean item = (ItemBean) session.getAttribute("item");
		long colorId = (long) session.getAttribute("colorId");
		if(!item.isFigureUploaded(colorId)){
			response.sendRedirect("/Store/upload/upload.jsp");
		}
		
		Set<Long> itemSizes = item.getSizes();
		String formParameter;
		String[] sizeDescriptions;
		for(long sizeId: itemSizes){
			formParameter = ""+sizeId+"[]";
			sizeDescriptions = parameterMap.get(formParameter);
			for(String description: sizeDescriptions){
				if(!description.trim().isEmpty()){
					item.addSizeDescripton(sizeId, description);
				}
			}
		}
		session.setAttribute("item", item);
	
		Gson gson = new Gson();
		System.out.println(gson.toJson(item));
		try {
			item.addToDB();
			System.out.println("The item id is: "+item.getId());
			response.sendRedirect("/Store/Success.html");
		} catch (DatabaseException e) {
			e.printStackTrace();
			response.sendRedirect("/Store/TechnicalDifficulties.html");
		}
		
	}
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		if(user==null || !user.getAccountType().equals("S")){
			response.sendRedirect("Login.html");
			return;
		}
		ItemBean item = (ItemBean) session.getAttribute("item");
		long colorId = (long) session.getAttribute("colorId");
		if(!item.isFigureUploaded(colorId)){
			response.sendRedirect("/Store/upload/upload.jsp");
			return;
		}
		response.sendRedirect("/Store/DefineProduct/DescribeSizes4.jsp");
		
	}

}



